'use strict';

const Controller = require('egg').Controller;

class UserControllor extends Controller {
  async index() {
    const { ctx } = this;
    // ctx.body = 'user index';
    const user = ctx.cookies.get('user') || '{}';
    // console.log(ctx.session.user);
    await ctx.render(
      'user.html',
      {
        id: 10,
        name: 'admin',
        list: [ 1, 2, 3, 4, 5, 6 ],
        user: JSON.parse(user),
      },
      {
        delimiters: '%',
      }
    );
  }

  async login() {
    const { ctx } = this;
    const body = ctx.request.body;
    // console.log(body);
    ctx.cookies.set('user', JSON.stringify(body), {
      maxAge: 1000 * 60,
    });
    ctx.session.user = body;
    console.log(body);
    ctx.body = {
      status: 200,
      data: body,
    };
  }

  async logout() {
    const { ctx } = this;
    ctx.cookies.set('user', null);
    ctx.body = {
      status: 200,
      data: null,
    };
  }

  async lists() {
    const { ctx } = this;
    // const res = await ctx.service.user.lists();
    const res = await ctx.model.User.findAll();

    ctx.body = res;
  }

  async detail() {
    // 获取路由参数
    const { ctx } = this;
    // const res = await ctx.service.user.detail(ctx.query.id);
    const res = await ctx.model.User.findByPk(ctx.query.id);
    // console.log(res);
    ctx.body = res;
  }

  async detail2() {
    // 获取路由动态参数
    const { ctx } = this;
    const res = await ctx.service.user.detail2(ctx.params.id);
    ctx.body = res;
  }

  async add() {
    // post
    const { ctx } = this;
    const body = ctx.request.body;
    // const res = ctx.service.user.add(body);
    const res = await ctx.model.User.create(body);
    const rules = {
      name: {
        type: 'string',
      },
      pwd: 'string',
    };
    ctx.validate(rules);
    ctx.body = {
      status: 200,
      data: {
        res,
      },
    };
  }

  async edit() {
    const { ctx } = this;
    const body = ctx.request.body;
    // const res = ctx.service.user.edit(body);
    const user = await ctx.model.User.findByPk(body.id);
    if (!user) {
      ctx.body = {
        status: 404,
        errMsg: 'ID 不存在',
      };
      return;
    }
    const res = user.update(body);
    ctx.body = {
      status: 200,
      data: res,
    };
  }

  async remove() {
    const { ctx } = this;
    const body = ctx.request.body;
    // const res = ctx.service.user.remove(body.id);
    const user = await ctx.model.User.findByPk(body.id);
    if (!user) {
      ctx.body = {
        status: 404,
        errMsg: 'ID 不存在',
      };
      return;
    }
    const res = user.destroy(body.id);
    ctx.body = res;
  }
}

module.exports = UserControllor;
